﻿using Flurl.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RsCms.UI.Models;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace RsCms
{
    public   partial class ApiHelper
    {
        IHttpContextAccessor HttpContextAccessor;
        public ApiHelper(IHttpContextAccessor httpContextAccessor)
        { 
            HttpContextAccessor = httpContextAccessor;
            FlurlHttp.Clients.WithDefaults(config =>
            {
                config.ConfigureHttpClient(x =>
                {
                    x.BaseAddress = new Uri(GetCurrentDomain());
                });
            });
        }
         string GetCurrentDomain()
        { 
            var currentDomain = $"{HttpContextAccessor.HttpContext.Request.Scheme}://{HttpContextAccessor.HttpContext.Request.Host}";
            return currentDomain;
        }
        public  async Task<SiteNavigateModel[]> GetNavigateAsync()
        {
            SiteNavigateModel[] target = new SiteNavigateModel[] { };
            try
            {
                var siteSettings = await GetSiteSettingsAsync();

                var setting = siteSettings?.FirstOrDefault(x => x.Key == "navigation");
              
                if (!string.IsNullOrWhiteSpace(setting.Value))
                {
                    return JsonSerializer.Deserialize<SiteNavigateModel[]>(setting.Value) ?? target;
                }
                return target;
            }
            catch (Exception)
            {
                return target;
            }
           
        }

        public async Task<SiteInfoModel>GetSiteInfoAsync()
        {
            SiteInfoModel info = new SiteInfoModel();
            try
            {
                string apiUrl = $"/api/settings/siteinfo";
                var data = await GetJsonAsync< SiteInfoModel> (apiUrl);
                return data;
            }
            catch (Exception)
            {
                return info;
            }
           
        }

        async Task< SettingsDto[]>GetSiteSettingsAsync()
        {
            string apiUrl = $"/api/settings/list?name=site";
            var data = await GetJsonAsync<SettingsDto[]>(apiUrl);
            return data;
        }

        /// <summary>
        /// 查询单个文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public  async Task<PostsModel> GetArticleAsync(string id)
        {
            try
            {
                string apiUrl = $"/api/posts/detail?id={id}";
                var data = await GetJsonAsync<PostsModel>(apiUrl);
                return data;
            }
            catch (Exception)
            {
                return new PostsModel();
            }
            
        }
		public async Task<PostsModel> GetArticleBySlugAsync(string slug)
		{
			try
			{
				string apiUrl = $"/api/posts/slug/{slug}";
				var data = await GetJsonAsync<PostsModel>(apiUrl);
				return data;
			}
			catch (Exception)
			{
				return new PostsModel();
			}

		}

        public async Task<PageData<ArticleItemModel>> PageArticleByTagAsync(int page,int pageSize,string tag)
        {
            try
            {
                string apiUrl = $"/api/posts/tag?page={page}&pagesize={pageSize}&tag={tag}";
                var data = await GetJsonAsync<PageData<ArticleItemModel>>(apiUrl);
                return data;
            }
            catch (Exception)
            {
                return new PageData<ArticleItemModel>
                {
                    Items = new List<ArticleItemModel>()
                };
            }
        }

        public async Task<SettingsDto[]> GetSettingsListAsync (string groupName)
        {
            var url = $"/api/settings/list?name={groupName}";
            var data=await GetJsonAsync<SettingsDto[]>(url);
            return data;
        }
      
		async Task<T> GetJsonAsync<T>(string apiUrl) where T:class
        { 
            var json = await apiUrl.GetStringAsync();

            var options = new JsonSerializerOptions();
            options.Converters.Add(new CustomDateConverter());

            var returnInfo = JsonSerializer.Deserialize<ReturnInfo<T>>(json,options);
             
            
            return returnInfo.Data;
        }
    }


    public class CustomDateConverter : JsonConverter<DateTime>
    {
        private const string Format = "yyyy-MM-dd HH:mm:ss";

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var dateString = reader.GetString();
            return DateTime.ParseExact(dateString, Format, null);
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(Format));
        }
    }
}
